package com.longyiqun.cm.controller.download;


import com.longyiqun.cm.domain.brokerResourceEntity;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

import static org.springframework.http.MediaType.APPLICATION_OCTET_STREAM_VALUE;

/**
 * program: CaseManager
 * package: com.longyiqun.cm.controller.download
 * author: 龙轶群
 * create: 2018-04-18 13:48
 **/

@RestController
@RequestMapping("/download")
public class DownloadRestControllerImpl {

    @Autowired
    private ServletContext servletContext;
    //http://192.168.200.41:8090/download/brokerResource?fileName=1531966453haha.mp4
    // 可以下载各种TYPE的资源 TIPS: APPLICATION_OCTET_STREAM_VALUE
    @RequestMapping(value = "/file", method = RequestMethod.GET, produces = APPLICATION_OCTET_STREAM_VALUE)
    public void downloadFile(HttpServletRequest request, HttpServletResponse response, @RequestParam String fileName ) throws ServletException, IOException {

        try {

            MediaType mediaType = MediaTypeUtils.getMediaTypeForFileName(this.servletContext, fileName);

            // FOR DEBUG
            System.out.println("fileName: " + fileName);
            System.out.println("mediaType: " + mediaType);

            response.setContentType(mediaType.getType());
            File file = new File("/home/tools/" +fileName);

            response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + fileName);

            response.setContentLength((int) file.length());

            BufferedInputStream inStream = new BufferedInputStream(new FileInputStream(file));
            BufferedOutputStream outStream = new BufferedOutputStream(response.getOutputStream());

            byte[] buffer = new byte[1024];
            int bytesRead = 0;
            while ((bytesRead = inStream.read(buffer)) != -1) {
                outStream.write(buffer, 0, bytesRead);
            }
            outStream.flush();
            inStream.close();
        } catch (Exception e) {
            System.out.print(e.getMessage());
        }
    }

}
